import api from '@/api'
import { useUserStoreToRefs, reset } from '@/store/useUserStore'
import { studioReset, useStudioStoreToRefs } from '@/store/useStudioStore'
import { useImStoreToRefs } from '@/store/useImStore'
import { resetUseCartStore } from "@/store/useCartStore";
import { getcId } from '@/hooks/useIm'
import CryptoJS from 'crypto-js';
export const isRegisterUser = (phone, registerWay = 0) => {
	return new Promise((resolve, reject) => {
		if (registerWay != 0) {
			resolve({
				data: []
			})
		} else {
			api({
				method: 'get',
				url: `/mall/user/v2/isRegister/${phone}`,
				isNotToken: true
			}).then((res : any) => {
				console.log(res)
				resolve(res)
			})
		}

	})
}
//切换账号
export const useLoginAccount = async (params) => {
	const deviceId = await getdeviceId()
	if(deviceId){
		uni.showLoading({
			mask: true,
			title: "切换账号中"
		})
		const { imServer } = useImStoreToRefs()
		const { access_token } = useUserStoreToRefs()
		let userId = params.userId || null
		const res : any = await api({
			url: `/mall/auth/switchUser?userId=${userId}&deviceId=${deviceId}`,
			method: 'POST'
		})
		console.log("切换账号", res)
		if (res.code == 0) {
			uni.showToast({
				mask: true,
				icon: 'none',
				title: "切换成功"
			})
			access_token.value = res.data
			await updateUserInfo()
			imServer.value.login()
			//切换成功后的返回路径
			uni.reLaunch({
				url: '/pages/home/index'
			});
				
		} else {
			uni.showToast({
				mask: true,
				icon: 'none',
				title: res.msg
			})
		}
				
		// console.log(res)
	}
	
}
//app一键登录
export const useLoginApp = async (params, callback : any = '') => {
	let phone = params.phone
	let userId = params.userId || null
	let step = params.step || ''
	const { access_token, refresh_token } = useUserStoreToRefs()
	const { imServer } = useImStoreToRefs()
	// 密码用AES加密
	let key = CryptoJS.enc.Utf8.parse('xuelanfang123456')
	let iv = key
	let sign = CryptoJS.AES.encrypt(
		'grant_type=open_id&origin=0&openId=' + phone,
		key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	}
	)
	console.log(sign.toString())
	const res : any = await api({
		url: `/auth/oauth/token?grant_type=open_id&origin=0&openId=${phone}&sign=${encodeURIComponent(
			sign.toString())}&userId=${userId}`,
		method: 'POST'
	})
	if (res.access_token) {
		access_token.value = res.access_token
		refresh_token.value = res.refresh_token
		uni.showToast({
			mask: true,
			icon: 'none',
			title: "登录成功!"
		})
		await updateUserInfo()
		saveAccountRecord()
		imServer.value.login()
		//登录成功后的返回路径
		const pages = getCurrentPages()
		// && (['pages/applyPetTeacher/index/index','pages/myStudio/studio/applyForDetails/index', 'pages/petsOrder/petsList/index','pages/im/message/index'].includes(pages[pages.length - 2].route))
		if (pages.length >= step) {
			uni.navigateBack({ delta: step - 1 })
		} else {
			uni.reLaunch({
				url: '/pages/home/index'
			});
		}
		callback && callback()
	} else {
		callback && callback()
		uni.showToast({
			mask: true,
			icon: 'none',
			title: res.msg
		})
	}
}
// 微信一键登录
export const useLoginWx = async (params, callback : any = '') => {
	let phone = params.phone
	let userId = params.userId || null
	let refereeId = params.refereeId || null
	let step = params.step || ''
	const { access_token, refresh_token } = useUserStoreToRefs()
	const { imServer } = useImStoreToRefs()
	uni.showLoading({
		mask: true,
		title: "登录中"
	})
	uni.login({
		success: async (res1) => {
			console.log(res1)
			const result : any = await api({
				method: 'post',
				url: '/mall/user/v2/loginBy2Code',
				data: {
					"refereeId": refereeId,
					"userId": userId,
					"origin": 2,
					"code": res1.code,
					"mobile": phone
				}
			})
			if (result.code == 0) {
				userId = userId || result.data.id
				const res : any = await api({
					method: 'post',
					url: `/auth/oauth/token?grant_type=open_id&origin=2&openId=${result.data.wxOpenId}&userId=${userId}`,
				})
				console.log(res)
				if (res.access_token) {
					access_token.value = res.access_token
					refresh_token.value = res.refresh_token
					uni.showToast({
						mask: true,
						icon: 'none',
						title: "登录成功!"
					})
					await updateUserInfo()
					saveAccountRecord()
					imServer.value.login()
					//登录成功后的返回路径
					const pages = getCurrentPages()
					// && (['pages/applyPetTeacher/index/index','pages/myStudio/studio/applyForDetails/index', 'pages/petsOrder/petsList/index','pages/im/message/index'].includes(pages[pages.length - 2].route))
					if (pages.length >= step) {
						uni.navigateBack({ delta: step - 1 })
					} else {
						uni.reLaunch({
							url: '/pages/home/index'
						});
					}
					callback && callback()
				} else {
					callback && callback()
					uni.showToast({
						mask: true,
						icon: 'none',
						title: res.msg
					})
				}
			} else {
				callback && callback()
				uni.showToast({
					mask: true,
					icon: 'none',
					title: "登录失败，请稍后重试"
				})
			}

		}
	})
}
export const useLoginPassword = async (params) => {
	let mobile = params.mobile
	let password = params.password
	let countryCode = params.countryCode
	let userId = params.userId
	let step = params.step
	const { access_token, refresh_token, shareRefereeId } = useUserStoreToRefs()
	const { imServer } = useImStoreToRefs()
	reset()
	uni.showLoading({
		mask: true,
		title: "登录中"
	})
	let key = CryptoJS.enc.Utf8.parse('xuelanfang123456')
	let iv = key
	let encryptedPasswd = CryptoJS.AES.encrypt(
		password,
		key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	}
	)
	const res : any = await api({
		method: 'post',
		isExecute: false,
		url: `/auth/mobile/token?mobile=${mobile}&countryCode=${countryCode}&passwd=${encodeURIComponent(encryptedPasswd.toString())}&userId=${userId}`
	})
	if (res.access_token) {
		access_token.value = res.access_token
		refresh_token.value = res.refresh_token
		uni.showToast({
			mask: true,
			icon: 'none',
			title: "登录成功"
		})
		await updateUserInfo()
		saveAccountRecord()
		imServer.value.login()
		//登录成功后的返回路径
		const pages = getCurrentPages()
		if (pages.length >= step) {
			uni.navigateBack({ delta: step - 1 })
		} else {
			uni.reLaunch({
				url: '/pages/home/index'
			});
		}
	} else {
		uni.showToast({
			mask: true,
			icon: 'none',
			title: res.msg
		})
	}
}
// 验证码登录
export const useLogin = async (params, callback : any = '') => {
	let mobile = params.mobile
	let code = params.code
	let countryCode = params.countryCode
	let userId = params.userId
	let step = params.step
	const { access_token, refresh_token, shareRefereeId } = useUserStoreToRefs()
	const { imServer } = useImStoreToRefs()
	reset()
	uni.showLoading({
		mask: true,
		title: "登录中"
	})
	const res : any = await api({
		method: 'post',
		url: `/auth/mobile/studio/token?mobile=${mobile}&code=${code}&type=login&countryCode=${countryCode}&refereeId=${shareRefereeId.value}&userId=${userId}`
	})
	if (res.access_token) {
		access_token.value = res.access_token
		refresh_token.value = res.refresh_token
		uni.showToast({
			mask: true,
			icon: 'none',
			title: "登录成功"
		})
		await updateUserInfo()
		saveAccountRecord()
		imServer.value.login()
		//当callback存在时时会返调用去在当前页面自定义跳转方式
		if (callback != '') {
			callback && callback()
			return
		}
		//登录成功后的返回路径
		const pages = getCurrentPages()
		if (pages.length >= step) {
			uni.navigateBack({ delta: step - 1 })
		} else {
			uni.reLaunch({
				url: '/pages/home/index'
			});
		}
	} else {
		uni.showToast({
			mask: true,
			icon: 'none',
			title: res.msg
		})
	}
}

//app中登录成功后保存此设备下的用户记录，用户切换账号时的用户
export const saveAccountRecord = async () => {
	const deviceId = await getdeviceId()
	if(deviceId){
		api({
			method: 'post',
			url: `/mall/auth/addDeviceLoginRecord/${deviceId}`
		}).then((res : any) => {
			console.log("保存设备id", res)
		})
	}
}
// 获取设备id
export const getdeviceId = () => {
	return new Promise((resolve) => {
		// #ifdef APP
		uni.getSystemInfo({
			success: (e) => {
				resolve(e.deviceId)
			}
		})
		// #endif
		// #ifndef APP
		resolve("")
		// #endif
	})

}
export const updateUserInfo = () => {
	const { access_token } = useUserStoreToRefs()
	console.log('access_token.value',access_token.value)
	const { userInfo } = useUserStoreToRefs()
	let { applicationRecord, workSpace } = useStudioStoreToRefs()
	return new Promise(async (resolve) => {
		const deviceId = await getdeviceId()
		console.log('deviceIddeviceId',deviceId)
		getcId()
		api({
			method: 'get',
			url: `/mall/user/detail?deviceId=${deviceId || ''}`
		}).then(async (res : any) => {
			console.log(res)
			res.data.avatar = res.data.tiktokAvatar || res.data.avatar
			res.data.nickName = res.data.tiktokNickName || res.data.nickName
			userInfo.value = res.data
			const resStudio : any = await api({
				method: 'get',
				url: `/mall/studio/petsitter-team/judgeUserStudio`
			})
			workSpace.value = resStudio.data
			//用户有工作室则显示首页工作室按钮
			if (resStudio.data) {
				applicationRecord.value = true
			} else {
				// 没有则看是否存在申请记录,存在则显示工作室按钮
				const resRecord : any = await api({
					method: 'get',
					url: `/mall/studio/apply-studio-record/getLatestRecordsByUserId`
				})
				console.log('resRecord', resRecord)
				applicationRecord.value = resRecord.data ? true : false
			}

			resolve(res)
		})
	})
}

export const logOut = () => {
	const { imServer, messagePoint } = useImStoreToRefs()
	return new Promise((resolve) => {
		try {
			api({
				method: 'DELETE',
				url: `/auth/token/logout`,
			})
		} catch (err) {
		}
		reset()
		studioReset()

		// 清除上传服务日常草稿
		uni.removeStorage({
			key: 'serviceRoutine'
		});
		uni.removeStorageSync('apply_pet_teacher');
		//清除申请陪宠师草稿
		resetUseCartStore()
		/* uni.removeStorage({
			key: 'apply_pet_teacher'
		}); */
		imServer.value.loginOut()
		messagePoint.value = 0 //清空消息数量
		// #ifdef APP-PLUS
		plus.runtime.setBadgeNumber(messagePoint.value)
		// #endif
		//多次执行时，如当前页面就是登录页面则不进行跳转
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const currentRoute = currentPage.route
		console.log(currentRoute)
		if (currentRoute != 'pages/login/index') {
			uni.navigateTo({
				url: '/pages/login/index'
			})
		}
		resolve(true)
	})
}

export const loginStatus = (callback ?, isComfirm ?, content = "请重新登录") => {
	const { userInfo } = useUserStoreToRefs()
	//不传递任何参数，根据登录状态返回用户信息或者false
	if (!callback) {
		return userInfo.value || false
	}

	return new Promise((resolve) => {
		if (userInfo.value) {
			callback && callback()
			resolve(true)
		} else {
			if (isComfirm == 'toast') {
				uni.showToast({
					icon: 'none',
					title: content
				})
			}
			if (isComfirm == 'showModal') {
				uni.showModal({
					title: '提示',
					content: content,
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/index'
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			}
			resolve(false)
		}
	})

}